<template>
    <view class="overall">
        
        <view class="content">

            <view class="manifest" v-for="(item, index) in defaultInfo" :key="index" @click="handleClick(item)">
                <view>
                    <view>
                        <view>{{item.nickname}} （{{item.relationship}}）</view>
                        <view class="default" v-if="item.status==1?true:false">默认</view>
                    </view>
                    <view>身份证号：{{item.code}}</view>
                    <view>就诊卡号：{{item.card}}</view>
                </view>
                <view>
                    <wd-icon name="arrow-right" size="22px"></wd-icon>
                </view>
            </view>
            <view class="manifest" v-for="(item, index) in cardInfo" :key="index" @click="handleClick(item)">
                <view>
                    <view>
                        <view>{{item.nickname}} （{{item.relationship}}）</view>
                        <view class="default" v-if="item.status==1?true:false">默认</view>
                    </view>
                    <view>身份证号：{{item.code}}</view>
                    <view>就诊卡号：{{item.card}}</view>
                </view>
                <view>
                    <wd-icon name="arrow-right" size="22px"></wd-icon>
                </view>
            </view>
            <wd-status-tip v-if="cardInfo.length==0 && defaultInfo.length==0 ?true:false" image="content"
                tip="暂未添加就诊卡" />

            <view class="add" @click="cardAdd()">
                <wd-icon name="add" size="22px"></wd-icon>
                <view>添加就诊人</view>
            </view>

        </view>
    </view>
</template>

<script>
    import { ref } from 'vue';
    import { card, visitEdit } from '@/api/index.js';

    export default {
        data() {
            return {
                userInfo: [],
                cardInfo: [],
                defaultInfo: []
            };
        },
        onShow() {
            this.defaultInfo = [];
            this.cardInfo = [];
            this.fun();
        },
        methods: {
            handleClickLeft() {
                uni.navigateBack();
            },
            
            // 获取用户ID的方法
            async getUserId() {
                try {
                    const res = await uni.getStorage({ key: 'user' });
                    return res.data?.data?.id;
                } catch (error) {
                    console.error('获取用户ID失败:', error);
                    uni.showToast({
                        title: '获取用户信息失败，请重新登录',
                        icon: 'none'
                    });
                    return null;
                }
            },
            
            async fun() {
                try {
                    const userId = await this.getUserId();
                    if (!userId) return;
                    
                    const res = await card({ user_id: userId });
                    console.log(res.data);
                    
                    if (res.data && res.data.length > 0) {
                        // 处理默认就诊人
                        const defaultItem = res.data.find(item => item.status === 1);
                        if (defaultItem) {
                            this.defaultInfo = [defaultItem];
                        }
                        
                        // 处理非默认就诊人
                        this.cardInfo = res.data.filter(item => item.status !== 1);
                        
                        // 如果没有默认就诊人，设置第一个为默认
                        if (!defaultItem && res.data.length > 0) {
                            await visitEdit({
                                status: 1,
                                tel: res.data[0].tel,
                                id: res.data[0].id,
                                user_id: res.data[0].user_id,
                            });
                            // 重新加载数据
                            this.fun();
                            return;
                        }
                        
                        this.userInfo = res.data[0];
                    } else {
                        // 没有就诊人数据，使用用户基本信息
                        const userRes = await uni.getStorage({ key: 'user' });
                        this.userInfo = userRes.data || [];
                    }
                } catch (error) {
                    console.error('加载就诊人数据失败:', error);
                    uni.showToast({
                        title: '网络错误，请稍后重试',
                        icon: 'none'
                    });
                }
            },

            cardAdd() {
                uni.navigateTo({
                    url: '/pages/addition/addition'
                });
            },
            
            handleClick(item) {
                uni.setStorage({
                    key: 'cardDetails',
                    data: item,
                    success: () => {
                        console.log('数据存储成功');
                    }
                });
                uni.navigateTo({
                    url: '/pages/detailsCard/detailsCard'
                });
            }
        }
    };
</script>

<style scoped>
    .overall {
        width: 100%;
        background-color: #F4F4F4;
        min-height: 100vh;
    }

    .title {
        width: 100%;
        height: 180rpx;
        background-color: #00DACA;
        color: white;
        display: flex;
        align-items: center;
    }

    .name {
        display: flex;
        align-items: center;
        font-weight: bold;
        font-size: 42rpx;
        margin-top: 50rpx;
        margin-left: 3%;
    }

    .name>view {
        margin-left: 20rpx;
    }

    .content {
        width: 100%;
    }

    .manifest {
        width: 90%;
        background-color: white;
        padding: 20rpx 5%;
        margin-top: 15rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .manifest>view:first-child>view:first-child {
        color: black;
        display: flex;
        width: 100%;
        justify-content: space-between;
        align-items: center;
    }

    .default {
        border: 1rpx #D8D8D8 solid;
        padding: 5rpx 10rpx;
    }

    .manifest>view:first-child>view {
        font-size: 30rpx;
        margin-bottom: 15rpx;
        color: #505050;
    }

    .images {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .images>image {
        object-fit: cover;
        width: 500rpx;
        height: 500rpx;
    }

    .add {
        width: 96%;
        margin: 15rpx 2%;
        background-color: #FFFFFF;
        color: #999999;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        align-items: center;
        height: 160rpx;
        border-radius: 5rpx;
    }
</style>